package com.example.demo.controller;

import com.example.demo.Entity.Comment;
import com.example.demo.Entity.CommentRequest;
import com.example.demo.Entity.Item;
import com.example.demo.Entity.User;
import com.example.demo.Service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/comments")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @PostMapping("/{itemId}")
    public ResponseEntity<Comment> addComment(
            @PathVariable("itemId") Long itemId,
            @RequestBody CommentRequest commentRequest) {

        Item item = commentService.getItemById(itemId);
        User user = commentService.getUserById(commentRequest.getUserId());

        Comment newComment = new Comment();
        newComment.setItem(item);
        newComment.setUser(user);
        newComment.setContent(commentRequest.getContent());
        newComment.setCreatedAt(LocalDateTime.now());

        Comment savedComment = commentService.save(newComment);

        return ResponseEntity.ok(savedComment);
    }



    @GetMapping("/{itemId}")
    public ResponseEntity<List<Comment>> getComments(@PathVariable Long itemId) {
        List<Comment> comments = commentService.getCommentsByItemId(itemId);
        return ResponseEntity.ok(comments);
    }
}
